package com.lhr.common.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;

import org.apache.commons.lang.StringUtils;

import com.lhr.common.util.domain.FreemarkerSetting;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

public class FreemarkerUtil {

	public static void build(FreemarkerSetting setting) throws IOException, TemplateException {

		// 模板所在的目录
		String templateDir = StringUtils.substringBeforeLast(setting.getTemplatePath(), File.separator);
		String templateName = StringUtils.substringAfterLast(setting.getTemplatePath(), File.separator);

		Configuration configuration = getDefaultConfiguration(templateDir);
		Template template = configuration.getTemplate(templateName, "UTF-8");
		Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(setting.getTargetPath())), "UTF-8"));
		template.process(setting.getData(), out);
		out.flush();
	}

	private static Configuration getDefaultConfiguration(String templateDir) throws IOException {
		Configuration configuration = new Configuration();
		configuration.setDefaultEncoding("UTF-8");
		configuration.setEncoding(Locale.CHINA, "UTF-8");
		configuration.setDirectoryForTemplateLoading(new File(templateDir));
		// 设置对象包装器
		configuration.setObjectWrapper(new DefaultObjectWrapper());
		// 设置异常处理器
		configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
		return configuration;
	}

}
